package yongxin.controller.reports;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.cgform.common.CommUtils;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.matchinegroup.MatchinegroupEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.rolling.RollingEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.matchinegroup.MatchinegroupServiceI;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.rolling.RollingServiceI;
import yongxin.service.tasks.TasksServiceI;
import yongxin.service.workshop.WorkshopServiceI;

/**   
 * @Title: Controller
 * @Description: 产成品月报表
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/finishedProductReportController")
public class FinishedProductReportController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FinishedProductReportController.class);

	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private RollingServiceI rollingService;
	@Autowired
	private TasksServiceI tasksService;
	@Autowired
	private WorkshopServiceI workshopService;
	@Autowired
	private MatchinegroupServiceI matchinegroupService;
	
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		
		return new ModelAndView("yongxin/reports/finishedProductReportList");
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
	
	String  sql = "  select  Top 10 *  from OpenQuery ";
	        sql += " (RemoteServer, ";
			sql += " '";
			sql += " select newid() id,A.Fyear 年,A.FPeriod 月,B.Fmodel FModel,B.FName FName,B.FNumber 物料代码,A.FBegBal AS   qcjc,A.freceive as sr,A.FSend  fc,A.FEndBal  jc"; 
			sql += " from Test.dbo.icbal A,Test.dbo.t_ICItem B  where A.FItemID =B.FItemID and B.fnumber like ''C.%''";
			sql += " ')";

		int count=0;
		List<Map<String,Object>> maplist=null;
		try{
			 
			// maplist=systemService.findForJdbcParam(sql, dataGrid.getPage(), dataGrid.getRows());
			// count=Integer.parseInt(systemService.findOneForJdbc(sql2, object).get("counts").toString());
			maplist = systemService.findForJdbc(sql);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
			
	//	 dataGrid.setPage(page);
		dataGrid.setTotal(10);
		dataGrid.setResults(maplist);
	//	 dataGrid.setFooter("create_date:1,ftrzl:2");
		TagUtil.datagrid(response, dataGrid);
		
		
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport,
			HttpServletRequest request) {

		AjaxJson j = new AjaxJson();
		String nprocess = request.getParameter("nprocess");
		String process = request.getParameter("process");

		if (processReport.getFbcph().split(",").length > 1) {
			String[] fbcph = processReport.getFbcph().split(",");

			String[] ftrkds = request.getParameterValues("ftrkd");
			String[] ftrhds = request.getParameterValues("ftrhd");
			String[] ftrzls = request.getParameterValues("ftrzl");
			String[] fcckds = request.getParameterValues("fcckd");
			String[] fcchds = request.getParameterValues("fcchd");
			String[] fcczls = request.getParameterValues("fcczl");
			String[] fbfzls = request.getParameterValues("fbfzl");
			String[] frates = request.getParameterValues("frate");
			String[] fnotes = request.getParameterValues("fnote");
			String[] fnprocesss = request.getParameterValues("nprocess");

			try {

				message = "工序汇报成功";
				ProcessReportEntity t = processReportService.get(
						ProcessReportEntity.class, processReport.getId());
				t.setFstate("3");
				t.setCreateBy(processReport.getCreateBy());
				t.setCreateDate(processReport.getCreateDate());
				processReportService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE,
						Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "工序汇报失败";
			}

			// 保存汇报记录
			for (int i = 0; i < fbcph.length; i++) {

				try {
					ProcessReportEntity t = new ProcessReportEntity();
					MyBeanUtils.copyBeanNotNull2Bean(processReport, t);

					t.setFbcph(fbcph[i]);
					t.setFtrhd(ftrhds[i]);
					t.setFtrkd(ftrkds[i]);
					t.setFtrzl(ftrzls[i]);
					t.setFcchd(fcchds[i]);
					t.setFcckd(fcckds[i]);
					t.setFcczl(fcczls[i]);
					t.setFbfzl(fbfzls[i]);
					t.setFrate(frates[i]);
					t.setFnote(fnotes[i]);
					t.setNprocess(fnprocesss[i]);

					processReportService.save(t);

					// 如果是轧机汇报 保存轧机工艺
					if (process != null
							&& (process.equals("p2_1") || process
									.equals("p2_2"))) {
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int j1 = 0; j1 < fkjhd.length; j1++) {

							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(t.getId());
							rolling.setFdc(String.valueOf(1 + j1));
							rolling.setFkjhd(fkjhd[j1]);
							rolling.setFsjhd(fsjhd[j1]);
							rolling.setFkjzl(fkjzl[j1]);
							rolling.setFsjzl(fsjzl[j1]);
							rolling.setFzzl(fzzl[j1]);
							rolling.setFsd(fsd[j1]);
							rolling.setFyxl(fyxl[j1]);
							rolling.setFzhxx(fzhxxs[j1]);
							rolling.setFhm(fhms[j1]);
							rolling.setFnote(note[j1]);
							rollingService.saveOrUpdate(rolling);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
					message = "工序汇报失败";
				}

			}

			if (processReport.getFstate().equals("2")) {
				// 保存一下工序待汇报记录
				for (int i = 0; i < fbcph.length; i++) {

					ProcessEntity entity = new ProcessEntity();
					entity.setFbcph(fbcph[i]);
					entity.setFprocess(fnprocesss[i]);
					processService.save(entity);
				}	
				for (int i = 0; i < fbcph.length; i++) {

					if (!fnprocesss[i].equals("over")) {
						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setCprocess(fnprocesss[i]);
						nprocessReport.setFbcph(fbcph[i]);
						nprocessReport.setFtrhd(fcchds[i]);
						nprocessReport.setFtrkd(fcckds[i]);
						nprocessReport.setFtrzl(fcczls[i]);
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);
					} else { // 计算任务单成材率

						boolean result = tasksService.checkISOver(fbcph[i].split("-")[0]);
						if (result) {
							double cczl = tasksService.computeCCZL(fbcph[i].split("-")[0]);
							double trzl = tasksService.selectTRZL(fbcph[i].split("-")[0]);
							String rate = tasksService.div(cczl, trzl);

							tasksService.computeRate(rate,fbcph[i].split("-")[0]);
						}
					}
				}
			}

		} else if (StringUtil.isNotEmpty(processReport.getId())) {
			message = "工序汇报成功";
			ProcessReportEntity t = processReportService.get(
					ProcessReportEntity.class, processReport.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
				processReportService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE,
						Globals.Log_Leavel_INFO);

				// 汇报
				if (processReport.getFstate().equals("2")) {
					ProcessEntity entity = new ProcessEntity();
					entity.setFbcph(processReport.getFbcph());
					entity.setFprocess(t.getNprocess());
					processService.save(entity);

					if (!t.getNprocess().equals("over")) {
						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setCprocess(t.getNprocess());
						nprocessReport.setFbcph(processReport.getFbcph());
						nprocessReport.setFtrhd(processReport.getFcchd());
						nprocessReport.setFtrkd(processReport.getFcckd());
						nprocessReport.setFtrzl(processReport.getFcczl());
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);

					} else { // 计算任务单成材率

						String bcph = processReport.getFbcph();
						if (bcph.split("-").length > 0) {
							bcph = bcph.split("-")[0];
						}
						boolean result = tasksService.checkISOver(bcph);
						if (result) {
							double cczl = tasksService.computeCCZL(bcph);
							double trzl = tasksService.selectTRZL(bcph);
							String rate = tasksService.div(cczl, trzl);

							tasksService.computeRate(rate,bcph);
						}
					}
					// 汇报 -保存轧制工序
					if (process != null
							&& (process.equals("p2_1") || process
									.equals("p2_2"))) {
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int i = 0; i < fkjhd.length; i++) {

							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(processReport.getId());
							rolling.setFdc(String.valueOf(1 + i));
							rolling.setFkjhd(fkjhd[i]);
							rolling.setFsjhd(fsjhd[i]);
							rolling.setFkjzl(fkjzl[i]);
							rolling.setFsjzl(fsjzl[i]);
							rolling.setFzzl(fzzl[i]);
							rolling.setFsd(fsd[i]);
							rolling.setFyxl(fyxl[i]);
							rolling.setFzhxx(fzhxxs[i]);
							rolling.setFhm(fhms[i]);
							rolling.setFnote(note[i]);
							rollingService.saveOrUpdate(rolling);
						}
					}

				} else if (processReport.getFstate().equals("1")) {

					// 保存轧机工艺
					if (process != null
							&& (process.equals("p2_1") || process
									.equals("p2_2"))) {
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int i = 0; i < fkjhd.length; i++) {
							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(processReport.getId());
							rolling.setFdc(String.valueOf(1 + i));
							rolling.setFkjhd(fkjhd[i]);
							rolling.setFsjhd(fsjhd[i]);
							rolling.setFkjzl(fkjzl[i]);
							rolling.setFsjzl(fsjzl[i]);
							rolling.setFzzl(fzzl[i]);
							rolling.setFsd(fsd[i]);
							rolling.setFyxl(fyxl[i]);
							rolling.setFzhxx(fzhxxs[i]);
							rolling.setFhm(fhms[i]);
							rolling.setFnote(note[i]);
							rollingService.saveOrUpdate(rolling);

						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				message = "工序汇报失败";
			}
		}

		j.setMsg(message);
		return j;
	}

	
	
	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ProcessReportEntity processReport, HttpServletRequest req) {
		
		if (StringUtil.isNotEmpty(processReport.getId())) {
			processReport = processReportService.getEntity(ProcessReportEntity.class, processReport.getId());
			List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
			req.setAttribute("workshopList", workshopList);
			req.setAttribute("processReportPage", processReport);
		}
		
		String process = processReport.getCprocess();
		
		if (process.equals("p2_1")) {
			String hql = "from RollingEntity where  1 = 1 AND fhbid = ?";
			List<RollingEntity> rollingList = systemService.findHql(hql,processReport.getId());
			req.setAttribute("rollingList", rollingList);
			return new ModelAndView("yongxin/process/processReport_p2_1");
			
		} else if (process.equals("p2_2")) {
			String hql = "from RollingEntity where  1 = 1 AND fhbid = ?";
			List<RollingEntity> rollingList = systemService.findHql(hql,processReport.getId());
			req.setAttribute("rollingList", rollingList);
			return new ModelAndView("yongxin/process/processReport_p2_2");
		} else if (process.equals("p4")) {
			return new ModelAndView("yongxin/process/processReport_p4");
		}  else if (process.equals("p8")) {
			return new ModelAndView("yongxin/process/processReport_p8");
		} else if (process.equals("p6")) {
			return new ModelAndView("yongxin/process/processReport_p6");
		} else {
			return new ModelAndView("yongxin/process/processReport");
		}

		
	}
	
	
	/*
	 * 获得机组列表
	 *  
	 */
	@RequestMapping(params = "getMatchinegroupList")
	@ResponseBody
	 public AjaxJson getMatchinegroupList(HttpServletRequest request){
		 
		String pid = request.getParameter("pid"); 
		String process = request.getParameter("process");
		if(process.split("_").length > 0){
			String[] processs = process.split("_");
			process = processs[0];
		}
		
		String sql = "select * from t_matchinegroup where p_id = ? and process = ?"; 
		List<Map<String,Object>> maplist=null;
		 try{
			 maplist=systemService.findForJdbc(sql, pid,process);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 String select="<select id='fmatchinegroup' name='fmatchinegroup'>";
			for (Map<String, Object> map : maplist) {
				select +="<option value="+map.get("name")+">"+map.get("name")+"</option>";
			}
		 
		 AjaxJson j = new AjaxJson();
		 j.setMsg(select);
		 //j.setObj(maplist);
		return j; 
		 
	 }
	
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		String pid = request.getParameter("pid"); 
		String ofbcph="";
		if(fbcph.indexOf("-")>0){
			ofbcph=fbcph.substring(0,fbcph.indexOf("-"));
		}
		Object[] object=new Object[2];
		object[0]=fbcph;
		object[1]=ofbcph;
		
		
		String sql="select tp.fbcph,tp.fprocess,tp.create_date,dic.typename from t_process tp ";
		sql +=" left join (select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql +=" where tst.typegroupid=tstg.ID ";
		sql +=" and tstg.typegroupcode='ccgx') dic ";
		sql +=" on tp.fprocess=dic.typecode ";
		sql +=" where fbcph=? or fbcph=? ";
		sql +=" order by tp.create_date ";
		
		
		String sql2="select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 +=" where tst.typegroupid=tstg.ID ";
		sql2 +=" and tstg.typegroupcode='ccgx'";
		
		List<Map<String,Object>> maplist=null;
		List<Map<String,Object>> maplist2=null;
		 try{
			 maplist=systemService.findForJdbc(sql, object);
			 maplist2=systemService.findForJdbc(sql2,null);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(maplist);
		 j.setMsg(createSelecte(maplist2));
		
		return j;
	}
	
	private String createSelecte(List<Map<String,Object>> maplist){
		String select="<select id='nprocess' name='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist) {
			select +="<option value="+map.get("typecode")+">"+map.get("typename")+"</option>";
		}
		return select;
	}
	
	
	
}
